package com.hx.xiao.controller;


import com.hx.xiao.entity.Users;
import com.hx.xiao.service.IUsersService;
import com.hx.xiao.utils.Code;
import com.hx.xiao.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hx
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/piyaoh/users")
public class UsersController {

    @Autowired
    private IUsersService iUsersService;

    @PostMapping("/login")
    public R loginPhone(@RequestBody Users users){
        Users userPhone = iUsersService.getUserPhone(users.getPhone());
        if (userPhone!=null){
            if (users.getKomh()!=null){
                return new R(Code.LOGIN_ERR,userPhone,"账户存在");
            }
                return new R(Code.LOGIN_OK,userPhone,"登入成功");
        }else {

            int i = iUsersService.addPhone(users);
            if (i>0){
                Users users1 = iUsersService.selectSuByid(users.getId());
                return new R(Code.SAVE_OK,users1,"添加成功");
            }else {
                return new R(Code.SAVE_ERRO,"添加失败");
            }
        }
    }

    @GetMapping("/all")
    public R findAll(){
        List<Users> all = iUsersService.findAll();
        if (all!=null){
            return new R(Code.GET_OK,all,"查询成功");
        }else {
            return new R(Code.GET_ERRO,"查询失败");
        }
    }


    @GetMapping("/find/{id}")
    private R findB(@PathVariable Integer id){
        Users b = iUsersService.findB(id);
        if (b!=null){
            return new R(Code.GET_OK,b,"查询成功");
        }else {
            return new R(Code.GET_ERRO,"查询失败");
        }
    }

    @GetMapping("/del/{id}")
    private R deleteB(@PathVariable Integer id){
        int i = iUsersService.deleteB(id);
        if (i>0){
            return new R(Code.DELETE_OK,"删除成功");
        }else {
            return new R(Code.DELETE_ERRO,"删除失败");
        }
    }

    @PostMapping("/up")
    private  R updaetB(@RequestBody Users users){
        int i = iUsersService.updateB(users);
        if (i>0){
            return new R(Code.UPDATE_OK,users,"修改成功");
        }else {
            return new R(Code.UPDATE_ERRO,"修改失败");
        }
    }

    @PostMapping("/add")
    private R addB(@RequestBody Users users){
        int i = iUsersService.addPhone(users);
        if(i>0){
            return new R(Code.GET_OK,users,"添加成功");
        }else {
            return new R(Code.GET_ERRO,"添加失败");
        }
    }

    @GetMapping("/fin/{username}/{komh}")
    private R findBy(@PathVariable String username,String komh){
        Users by = iUsersService.findBy(username,komh);
        if(by!=null){
            return new R(Code.GET_OK,by,"查询成功");
       }else {
            return new R(Code.GET_ERRO,"查询失败");
        }
    }
}
